package vincent.com.layouttest.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;

/**
 * Created by chenzhengwen on 2015/3/12.
 */
public class CrossView extends View {
    private final int DEFAULT_SIZE = 100;
    private Paint mPaint;

    public CrossView(Context ctx, AttributeSet attrs){
        super(ctx, attrs);
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setColor(Color.BLACK);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension(calculate(widthMeasureSpec), calculate(heightMeasureSpec));
    }

    private int calculate(int measureSpec){
        int defaultSize = (int)(DEFAULT_SIZE * getContext().getResources().getDisplayMetrics().density);

        int specMode = MeasureSpec.getMode(measureSpec);
        int size = MeasureSpec.getSize(measureSpec);

        if(MeasureSpec.EXACTLY == specMode){
            return size;
        }

        if(MeasureSpec.AT_MOST == specMode){
            return Math.min(size, defaultSize);
        }

        return defaultSize;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        float[] mLinesData = {0.5f, 0f, 0.5f, 1f,
                                0f, 0.5f, 1f, 0.5f};

        int scale = getWidth();
        canvas.save();

        canvas.scale(scale, scale);
        canvas.drawLines(mLinesData, mPaint);

        canvas.restore();
    }
}
